<template>
	<div style="height: 100%;">
		<div style="padding: 10px;background: #fff;border-radius: 8px;margin-bottom: 10px;">
			<el-button name="toJSON" @click="saveInfo" class="item-space" size="small" type="primary">
				保存
			</el-button>
		</div>

		<div style="position: relative;height: calc(100% - 80px);">
			<div id="container" style="width: 100%; height:100%;"></div>
			<div id="minimap" style="position: absolute;right: 0;top: 0;text-align: left;"></div>
		</div>


		<el-dialog :visible.sync="visible2" :close-on-click-modal="false" title="类型" top="5%" width="30%">
			<el-form ref="form" label-width="120px">
				<el-form-item label="类型" prop="type">
					<el-select v-model="saveParams.type" placeholder="请选择">
						<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item v-if="saveParams.type=='DEFENCE'" label="防治设施" required>
					<el-select placeholder="请选择" v-model="saveParams.itemId">
						<el-option v-for="item in defenceList" :key="item.id" :label="item.defenceName+'('+item.defenceNo+')'"
							:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item v-if="saveParams.type=='LINK'" label="产污环节" prop="type" required>
					<el-select placeholder="请选择" v-model="saveParams.itemId">
						<el-option v-for="item in technologyList" :key="item.id" :label="item.linkName+'('+item.linkCode+')'"
							:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item style="text-align: center;margin-left: -90px!important;">
					<el-button type="primary" @click="saveItem">保存</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
		
		<waterDefenceManage ref="waterDefenceManage" @success="editDefenceSuccess"></waterDefenceManage>
		<linkManage ref="linkManage" @success="editLinkSuccess" linkType="WATER_LINK"></linkManage>
	</div>
</template>

<script>
	import {
		Graph,
		Cell,
		Node,
		Path
	} from '@antv/x6'
	import {
		Scroller
	} from "@antv/x6-plugin-scroller";
	import {
		MiniMap
	} from "@antv/x6-plugin-minimap";

	import Hierarchy from '@antv/hierarchy'
	import insertCss from 'insert-css'
	import toolBar from '@/components/toolBar/index'
	import waterDefenceManage from '@/components/wasteWater/waterDefenceManage'
	import linkManage from '@/components/baseInfo/lineLinkManage'

	let that
	export default {
		components: {
			toolBar,
			waterDefenceManage,
			linkManage
		},
		data() {
			return {
				visible2: false,
				params: {
					lineId: '',
					jsonData: '',
				},
				options: [{
					label: "防治设施",
					value: "DEFENCE"
				}, {
					label: "产污环节",
					value: "LINK"
				}],
				saveParams: {
					type: 'DEFENCE',
					itemId: '',
					itemName: '',
				},
				selectNode: '',
				graph: '',
				graphData: '',

				technologyList: [],
				defenceList: [],
			}
		},
		created: function() {},
		mounted: function() {
			that = this
			that.params.ticketId = that.$store.state.token
			if (localStorage.getItem("outlet")) {
				let thisLine = JSON.parse(localStorage.getItem("outlet"))
				that.outlet = {
					id: thisLine.outletId,
					waterOutletName: thisLine.outletName,
				}
				that.params.lineId = thisLine.id

				if (!thisLine.jsonData || thisLine.jsonData == "null") {
					that.graphData = {
						id: that.outlet.id,
						type: 'OUTLET',
						label: that.outlet.waterOutletName,
						width: 160,
						height: 50,
					}
				} else {
					that.graphData = JSON.parse(thisLine.jsonData)
				}
			}

			that.getDefenceList()
			that.getTechnologyDataList()

			that.registerNode()

			that.graph = new Graph({
				container: document.getElementById('container'),
				background: {
					color: '#fff' // 设置画布背景颜色
				},
				grid: {
					size: 10,
					visible: true,
					type: 'dot', // 'dot' | 'fixedDot' | 'mesh'
					args: {
						color: '#a0a0a0', // 网格线/点颜色
						thickness: 1, // 网格线宽度/网格点大小
					},
				},
				mousewheel: {
					enabled: true,
					modifiers: ['ctrl', 'meta'],
					minScale: 0.5,
					maxScale: 2,
				},
				interacting: {
					nodeMovable: true, //节点是否可以被移动。
					edgeMovable: false, //边是否可以被移动。
					edgeLabelMovable: false, //边的标签是否可以被移动。
					arrowheadMovable: false, //边的起始/终止箭头是否可以被移动
					vertexMovable: true, //边的路径点是否可以被移动。
					vertexAddable: true, //是否可以添加边的路径点。
					vertexDeletable: true, //边的路径点是否可以被删除。
				},
				selecting: {
					enabled: true,
				},
				keyboard: {
					enabled: true,
				},
			})
			that.graph.use(
				new Scroller({
					pannable: true,
					enabled: true,
					autoResize: true,
				})
			);
			that.graph.use(
				new MiniMap({
					container: document.getElementById("minimap"),
				})
			);

			that.graph.on('add:OUTLET', ({
				node
			}) => {
				that.saveParams = that.$options.data().saveParams
				that.selectNode = node
				that.visible2 = true
			})
			
			that.graph.on('update:OUTLET', ({
				node
			}) => {
				console.log(node)
				that.ajax({
					url: '/waterOutletDefence/getWaterDefenceByDefenceId?ticketId=' + that.params
						.ticketId,
					data: {
						defenceId: node.id
					},
					contentType: 'application/x-www-form-urlencoded',
					success: function(result) {
						if (result.data) {
							that.$refs.waterDefenceManage.editThis(result.data)
						}
					},
				})
			})
			
			that.graph.on('update:LINK', ({
				node
			}) => {
				that.$refs.linkManage.editThis(node)
			})

			//console.log(that.graphData)
			that.render()
		},

		methods: {
			
			editLinkSuccess(link){
				let id = link.id
				const res = that.findItem(that.graphData, id)
				console.log(link)
				const dataItem = res.parent
				if (dataItem && dataItem.children) {
					const {
						children
					} = dataItem
					const index = children.findIndex((item) => item.id === id)
					that.$set(children, index, {
						id: link.id,
						type: "LINK",
						label: link.linkName,
						width: 100,
						height: 40,
					})
					that.render()
				}
			},
			
			editDefenceSuccess(defence) {
				let id = defence.id
				const res = that.findItem(that.graphData, id)
				console.log(defence)
				const dataItem = res.parent
				if (dataItem && dataItem.children) {
					const {
						children
					} = dataItem
					const index = children.findIndex((item) => item.id === id)
					that.$set(children, index, {
						id: defence.id,
						type: "DEFENCE",
						label: defence.defenceName,
						width: 100,
						height: 40,
					})
					that.render()
				}
			},

			saveInfo() {
				//console.log(that.graphData)
				//that.params.jsonData = that.graph.toJSON().cells
				that.params.jsonData = that.graphData
				that.ajax({
					url: '/waterOutletLine/saveWaterOutletLineDetail?ticketId=' + that.params
						.ticketId,
					data: JSON.stringify(that.params),
					contentType: 'application/json',
					success: function(result) {
						if (result.data) {
							that.$message.success("保存成功！")
							let thisGraphData = {
								jsonData: JSON.stringify(that.params.jsonData)
							}
							localStorage.setItem("outlet", JSON.stringify(thisGraphData))
						}
					},
				})
			},

			saveItem() {
				if (!that.saveParams.itemId) return that.$message.error("请填写完整")
				if (that.saveParams.type == 'DEFENCE') {
					let thisIndex = that.defenceList.findIndex(item => item.id == that.saveParams.itemId)
					if (thisIndex != -1) that.saveParams.itemName = that.defenceList[thisIndex].defenceName + "(" + that
						.defenceList[thisIndex].defenceNo + ")"
				} else if (that.saveParams.type == 'LINK') {
					let thisIndex = that.technologyList.findIndex(item => item.id == that.saveParams.itemId)
					if (thisIndex != -1) that.saveParams.itemName = that.technologyList[thisIndex].linkName + "(" + that
						.technologyList[thisIndex].linkCode + ")"
				}
				that.visible2 = false
				if (that.addChildNode()) that.render()
			},

			render() {
				const result = Hierarchy.mindmap(that.graphData, {
					direction: 'H',
					getHeight(d) {
						return d.height
					},
					getWidth(d) {
						return d.width
					},
					getHGap() {
						return 40
					},
					getVGap() {
						return 20
					},
					getSide: () => {
						return 'right'
					},
				})
				const cells = []
				const traverse = (hierarchyItem) => {
					if (hierarchyItem) {
						const {
							data,
							children
						} = hierarchyItem

						cells.push(
							that.graph.createNode({
								id: data.id,
								shape: data.type,
								x: hierarchyItem.x,
								y: hierarchyItem.y,
								width: data.width + 20,
								height: data.height + 40,
								label: that.subStr(data.label),
								type: data.type,
							}),
						)
						if (children) {
							children.forEach((item) => {
								const {
									id,
									data
								} = item
								cells.push(
									that.graph.createEdge({
										shape: 'mindmap-edge',
										source: {
											cell: hierarchyItem.id,
										},
										target: {
											cell: id,
											anchor: {
												name: 'left',
											},
										},
									}),
								)
								traverse(item)
							})
						}
					}
				}

				traverse(result)
				that.graph.resetCells(cells)
				that.graph.centerContent()
			},


			subStr(str) {
				// 设置变量存储返回值
				let newstr = "";
				// 如果长度超过5，就要截取插入字符
				if (str.length > 7) {
					// 第一次截取
					newstr = str.slice(0, 7) + "\n";
					// 闭包再次调用，如果截取后的字段长度依然超过5，再次调用，如果没有直接返回当前值
					return newstr + that.subStr(str.slice(7));
				} else {
					// 直接返回当前值 
					return str
				}
			},


			findItem(obj, id) {
				//console.log(obj, id)
				if (obj.id === id) {
					return {
						parent: null,
						node: obj,
					}
				}
				const {
					children
				} = obj
				if (children) {
					for (let i = 0, len = children.length; i < len; i++) {
						const res = that.findItem(children[i], id)
						if (res) {
							return {
								parent: res.parent || obj,
								node: res.node,
							}
						}
					}
				}
				return null
			},


			addChildNode() {
				const res = that.findItem(that.graphData, that.selectNode.id)
				const dataItem = res.node
				let type
				if (that.saveParams.type == "DEFENCE") type = "DEFENCE"
				if (that.saveParams.type == "LINK") type = "LINK"

				let item = {
					id: that.saveParams.itemId,
					type: type,
					label: that.saveParams.itemName,
					width: 100,
					height: 40,
				}

				if (dataItem.children) {
					dataItem.children.push(item)
				} else {
					dataItem.children = [item]
				}
				return item
			},


			removeNode(id) {
				const res = that.findItem(that.graphData, id)
				const dataItem = res.parent
				if (dataItem && dataItem.children) {
					const {
						children
					} = dataItem
					const index = children.findIndex((item) => item.id === id)
					return children.splice(index, 1)
				}
				return null
			},

			//注册节点
			registerNode() {
				insertCss(`
				  .topic-image {
				    cursor: pointer;
				  }
				`)
				// 排口
				Graph.registerNode(
					'OUTLET', {
						inherit: 'rect',
						markup: [{
								tagName: 'rect',
								selector: 'body',
							},
							{
								tagName: 'image',
								selector: 'img',
							},
							{
								tagName: 'text',
								selector: 'label',
							},
						],
						//tools: "button-remove",
						attrs: {
							body: {
								rx: 10,
								ry: 10,
								refWidth: '100%',
								refHeight: '100%',
								fill: '#85C9B5',
								stroke: '#85C9B5',
								strokeWidth: 1,
							},
							img: {
								ref: 'body',
								refX: '100%',
								refY: '50%',
								refY2: -8,
								width: 16,
								height: 16,
								'xlink:href': 'https://gw.alipayobjects.com/mdn/rms_43231b/afts/img/A*SYCuQ6HHs5cAAAAAAAAAAAAAARQnAQ',
								event: 'add:OUTLET',
								class: 'topic-image',
							},
							label: {
								fontSize: 14,
								fill: '#fff',
								textAnchor: 'middle',
								textVerticalAnchor: 'middle',
							},
						},
					},
					true,
				)

				// 设施
				Graph.registerNode(
					'DEFENCE', {
						inherit: 'rect',
						markup: [{
								tagName: 'rect',
								selector: 'body',
							},
							{
								tagName: 'image',
								selector: 'img',
							},
							{
								tagName: 'image',
								selector: 'img2',
							},
							{
								tagName: 'text',
								selector: 'label',
							},
						],
						tools: [{
							name: 'button-remove',
							args: {
								onClick(e) {
									that.removeNode(e.cell.id)
									that.render()
									console.log(e)
								}
							}
						}],
						attrs: {
							body: {
								rx: 10,
								ry: 10,
								refWidth: '100%',
								refHeight: '100%',
								fill: '#3a3ef4',
								stroke: '#3a3ef4',
								strokeWidth: 1,
							},
							img: {
								ref: 'body',
								refX: '100%',
								refY: '20%',
								refY2: -8,
								width: 16,
								height: 16,
								'xlink:href': 'https://gw.alipayobjects.com/mdn/rms_43231b/afts/img/A*SYCuQ6HHs5cAAAAAAAAAAAAAARQnAQ',
								event: 'add:OUTLET',
								class: 'topic-image',
							},
							img2: {
								ref: 'body',
								refX: '100%',
								refY: '80%',
								refY2: -8,
								width: 16,
								height: 16,
								'xlink:href': 'https://qiniu.jimuzhou.cloud/edit.png',
								event: 'update:OUTLET',
								class: 'topic-image',
							},
							label: {
								fontSize: 14,
								fill: '#fff',
								ellipsis: true, // 文本超出显示范围时，自动添加省略号
								breakWord: true, // 是否截断单词

							},
						},
					},
					true,
				)


				// 环节
				Graph.registerNode(
					'LINK', {
						inherit: 'rect',
						markup: [{
								tagName: 'rect',
								selector: 'body',
							},
							{
								tagName: 'text',
								selector: 'label',
							},{
								tagName: 'image',
								selector: 'img2',
							},
						],
						tools: [{
							name: 'button-remove',
							args: {
								onClick(e) {
									that.removeNode(e.cell.id)
									that.render()
									console.log(e)
								}
							}
						}],

						attrs: {
							body: {
								rx: 10,
								ry: 10,
								refWidth: '100%',
								refHeight: '100%',
								fill: '#F9D88F',
								stroke: '#F9D88F',
								strokeWidth: 1,
							},img2: {
								ref: 'body',
								refX: '100%',
								refY: '50%',
								refY2: -8,
								width: 16,
								height: 16,
								'xlink:href': 'https://qiniu.jimuzhou.cloud/edit.png',
								event: 'update:LINK',
								class: 'topic-image',
							},
							label: {
								fontSize: 14,
								fill: '#fff',
							},
						},
					},
					true,
				)

				// 连接器
				Graph.registerConnector(
					'mindmap',
					(sourcePoint, targetPoint, routerPoints, options) => {
						const midX = sourcePoint.x + 10
						const midY = sourcePoint.y
						const ctrX = (targetPoint.x - midX) / 5 + midX
						const ctrY = targetPoint.y
						const pathData = `
				     M ${sourcePoint.x} ${sourcePoint.y}
				     L ${midX} ${midY}
				     Q ${ctrX} ${ctrY} ${targetPoint.x} ${targetPoint.y}
				    `
						return options.raw ? Path.parse(pathData) : pathData
					},
					true,
				)

				// 边
				Graph.registerEdge(
					'mindmap-edge', {
						inherit: 'edge',
						connector: {
							name: 'mindmap',
						},
						markup: [{
								tagName: 'path',
								selector: 'stroke',
							},
							{
								tagName: 'path',
								selector: 'fill',
							},
						],
						connector: {
							name: 'smooth'
						},
						attrs: {
							fill: {
								connection: true,
								strokeWidth: 12,
								strokeLinecap: 'round',
								fill: 'none',
								// 渐变使用教程：https://x6.antv.vision/zh/docs/api/registry/attr#fill
								stroke: '#fff',
							},
							stroke: {
								fill: 'none',
								stroke: '#999',
								connection: true,
								strokeWidth: 14,
								strokeLinecap: 'round',
							},
						},
						zIndex: 0,
					},
					true,
				)
			},

			getDefenceList() {
				that.ajax({
					url: '/waterOutletDefence/getWaterDefenceListByOutletId',
					data: {
						//outletId: that.outletId,
					},
					contentType: 'application/x-www-form-urlencoded',
					success: function(result) {
						if (result.data) {
							that.defenceList = result.data
						}
					},
				})
			},

			getTechnologyDataList() {
				that.ajax({
					url: '/waterLink/getInUseWaterLinkList',
					data: JSON.stringify({
						//outletId: that.outletId,
					}),
					contentType: 'application/json',
					success: function(result) {
						if (result.data) {
							that.technologyList = result.data
						}
					},
				})
			},


		}
	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>